use crate::core::settings::load_settings;
use crate::ui::window::{calculate_window_size, calculate_center_position};
use tauri::{LogicalSize, LogicalPosition, Manager};
use tauri_plugin_global_shortcut::{Code, Modifiers, Shortcut as GlobalShortcut, GlobalShortcutExt};
use log::{debug, warn};

/// 解析修饰键字符串为Modifiers
fn parse_modifiers(modifiers: &[String]) -> Option<Modifiers> {
    if modifiers.is_empty() {
        return None;
    }
    
    let mut result = Modifiers::empty();
    for modifier in modifiers {
        match modifier.as_str() {
            "Ctrl" => result |= Modifiers::CONTROL,
            "Alt" => result |= Modifiers::ALT,
            "Shift" => result |= Modifiers::SHIFT,
            "Cmd" | "Super" => result |= Modifiers::SUPER,
            _ => continue,
        }
    }
    
    if result.is_empty() {
        None
    } else {
        Some(result)
    }
}

/// 解析按键字符串为Code
fn parse_key_code(key: &str) -> Option<Code> {
    match key {
        "Space" => Some(Code::Space),
        "Enter" => Some(Code::Enter),
        "Tab" => Some(Code::Tab),
        "Escape" => Some(Code::Escape),
        "F1" => Some(Code::F1),
        "F2" => Some(Code::F2),
        "F3" => Some(Code::F3),
        "F4" => Some(Code::F4),
        "F5" => Some(Code::F5),
        "F6" => Some(Code::F6),
        "F7" => Some(Code::F7),
        "F8" => Some(Code::F8),
        "F9" => Some(Code::F9),
        "F10" => Some(Code::F10),
        "F11" => Some(Code::F11),
        "F12" => Some(Code::F12),
        _ => None,
    }
}

/// 根据设置注册全局快捷键
pub fn register_shortcuts_from_settings(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
    let settings = load_settings().unwrap_or_default();
    
    // 注册显示窗口快捷键
    if let (Some(modifiers), Some(key_code)) = (
        parse_modifiers(&settings.show_shortcut_modifiers),
        parse_key_code(&settings.show_shortcut_key)
    ) {
        let show_shortcut = GlobalShortcut::new(Some(modifiers), key_code);
        let app_handle = app.handle().clone();
        
        app.global_shortcut().on_shortcut(show_shortcut, move |_app, _shortcut, _event| {
            if let Some(window) = app_handle.get_webview_window("main") {
                // 重新计算窗口大小和居中位置
                let (width, height) = calculate_window_size();
                let (x, y) = calculate_center_position(width, height);
                
                // 设置窗口大小和位置
                let _ = window.set_size(LogicalSize::new(width, height));
                let _ = window.set_position(LogicalPosition::new(x, y));
                
                // 显示并聚焦窗口
                let _ = window.show();
                let _ = window.set_focus();
            }
        })?;
        
        match app.global_shortcut().register(show_shortcut) {
            Ok(_) => {
                debug!("显示窗口快捷键注册成功: {:?}+{:?}", modifiers, key_code);
            }
            Err(e) => {
                warn!("显示窗口快捷键注册失败: {}", e);
            }
        }
    }
    
    // 注册隐藏窗口快捷键
    let hide_modifiers = parse_modifiers(&settings.hide_shortcut_modifiers);
    if let Some(hide_key_code) = parse_key_code(&settings.hide_shortcut_key) {
        let hide_shortcut = GlobalShortcut::new(hide_modifiers, hide_key_code);
        let app_handle_hide = app.handle().clone();
        
        app.global_shortcut().on_shortcut(hide_shortcut, move |_app, _shortcut, _event| {
            debug!("隐藏窗口快捷键被触发");
            
            if let Some(window) = app_handle_hide.get_webview_window("main") {
                match window.is_visible() {
                    Ok(true) => {
                        debug!("隐藏窗口到托盘");
                        let _ = window.hide();
                    }
                    Ok(false) => {
                        debug!("窗口已经隐藏");
                    }
                    Err(e) => {
                        debug!("检查窗口可见性时出错: {}", e);
                    }
                }
            } else {
                debug!("无法获取主窗口");
            }
        })?;
        
        match app.global_shortcut().register(hide_shortcut) {
            Ok(_) => {
                debug!("隐藏窗口快捷键注册成功: {:?}+{:?}", hide_modifiers, hide_key_code);
            }
            Err(e) => {
                warn!("隐藏窗口快捷键注册失败: {}", e);
            }
        }
    }
    
    Ok(())
}